package com.xiyin.controller;


import com.xiyin.entity.User;
import com.xiyin.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 功能点：1.mybatisplus 默认给字段设置null时，更新字段不会生效，如果想让字段生效需要添加@TableField(updateStrategy = FieldStrategy.IGNORED)注解;
 * @author xukaihang
 * @since 2024-08-17
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    //新增
    @PostMapping ("/add")
    public ResponseEntity<User> save(@RequestBody User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        boolean save = userService.save(user);
        return ResponseEntity.ok(save ? user : null);
    }
    //查询
    @GetMapping("{id}")
    public ResponseEntity<User> queryById(@PathVariable("id") Long id) {
        return ResponseEntity.ok(userService.getById(id));
    }
    //修改
    @PostMapping("/update")
    public ResponseEntity<User> update(@RequestBody User user) {
        //默认情况设置为null，更新的字段不会生效
        user.setUserName(null);
        user.setUpdateTime(null);
        return ResponseEntity.ok(userService.updateById(user)? user : null);
    }
    //删除
    @PostMapping("/delete/{id}")
    public ResponseEntity<Boolean> delete(@PathVariable("id") Long id) {
        return ResponseEntity.ok(userService.removeById(id));
    }
}
